package com.atguigu.tingshu.order.receiver;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.order.service.MqOpsService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * <a href="https://www.shallowrecall.top/">Recall`Blog</a></br>
 * <a href="https://github.com/ShallowRecall">GitHub</a>
 *
 * @author Recall
 * @createTime 2025/06/10 18:27
 **/
@Component
public class OrderInfoReceiver {

    @Autowired
    private MqOpsService mqOpsService;


    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_LOCAL_MSG, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_LOCAL_MSG, durable = "true"),
            key = MqConst.ROUTING_LOCAL_MSG))
    @SneakyThrows   // SneakyThrows可以绕开编译时候的异常 但是真正在运行期间出现异常依然会抛出来
    public void listenUpdateLocalMsgStatus(String content, Message message, Channel channel) {

        // 1.判断消息是否存在
        if (StringUtils.isEmpty(content)) {
            return;  // 不用消费
        }
        // 2.消费消息
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        mqOpsService.updateLocalMsgStatus(content);
        // 4.手动应答消息（将消息从队列中删除掉）
        channel.basicAck(deliveryTag, false);

    }

    @RabbitListener(queues = {MqConst.QUEUE_CANCEL_ORDER})
    @SneakyThrows   // SneakyThrows可以绕开编译时候的异常 但是真正在运行期间出现异常依然会抛出来
    public void listenCancelOrder(String orderNo, Message message, Channel channel) {
        // 1.判断消息是否存在
        if (StringUtils.isEmpty(orderNo)) {
            return;  // 不用消费
        }
        // 2.消费消息
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        mqOpsService.cancelOrder(orderNo);
        // 4.手动应答消息（将消息从队列中删除掉）
        channel.basicAck(deliveryTag, false);
    }

}
